package com.wocai.jrt.orgadmin.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;

import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vteba.common.exception.ServiceException;
import com.vteba.utils.common.PropUtils;

public class ApiCallUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(ApiCallUtils.class);
	private static final int TIMEOUT = 10 * 1000;
	private static String hostName;
	private static int port;
	private static String schema;
	private static String url;
	private static String token;
	private static HttpHost host;
	
	
	static {
		hostName = PropUtils.get("api.address");
		port = PropUtils.getInt("api.port");
		schema = PropUtils.get("api.schema");
		url = PropUtils.get("api.url");
		token = PropUtils.get("api.token");
		host = new HttpHost(hostName,port,schema);
    }
	
	
	
	public static int callToCreateContact(String orderId){
		
		HttpPost httpPost = null;
		try {
			httpPost = buildHttpPost("orderId="+orderId+"&tokenId="+token, schema+"://"+hostName+":"+port+"//"+url);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			throw new ServiceException(e1.getMessage());
		}
		try {
			// 创建客户端
			CloseableHttpClient httpClient = HttpClientBuilder.create().build();
			if (LOGGER.isInfoEnabled()) {
				LOGGER.info("request url is [{}]",httpPost.getURI());
			}
			// 发起调用
			CloseableHttpResponse httpResponse = httpClient.execute(host, httpPost);
			int status = httpResponse.getStatusLine().getStatusCode();
			String bytes = null;
			if (status == 200) {// 结果正常
				bytes = EntityUtils.toString(httpResponse.getEntity(), Charset.forName("UTF-8"));
			} else {// 结果异常
				LOGGER.error("请求的urlPath错误[{}]，响应码是[{}]", httpPost.getURI().toString(), status);
				httpResponse.close();
				httpClient.close();
				return 0;
			}
			if (LOGGER.isInfoEnabled()) {
				LOGGER.info("executing post request success，result is :[{}]",bytes);
			}
			httpResponse.close();
			httpClient.close();
		} catch (ClientProtocolException e) {
			LOGGER.error("[{}]请求，客户端协议错误。", httpPost.getURI().toString(), e.getMessage());
			return 0;
		} catch (IOException e) {
			LOGGER.error("[{}]请求IO错误。", httpPost.getURI().toString(), e);
			return 0;
		}
		return 1;
	}
	
	private static HttpPost buildHttpPost(final String paramString, final String api) throws UnsupportedEncodingException {
		// 构建请求uri
		URI uri = null;
		try {
			URIBuilder uriBuilder = new URIBuilder();
			// 设置请求的路径
			uriBuilder.setPath(api);
			uri = uriBuilder.build();
		} catch (URISyntaxException e1) {
			LOGGER.error("HttpClient创建URI错误。可能传递的参数错误。", e1.getMessage());
			return null;
		}

		// 设置post请求
		HttpPost httpPost = new HttpPost(uri);
		StringEntity stringEntity = new StringEntity(paramString,Charset.forName("utf-8"));
		stringEntity.setContentEncoding("UTF-8");
		stringEntity.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
		httpPost.setEntity(stringEntity);

		RequestConfig config = RequestConfig.custom().setSocketTimeout(TIMEOUT)
				.setConnectTimeout(TIMEOUT).build();
		httpPost.setConfig(config);
		return httpPost;
	}
}
